﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

// Directives
using Microsoft.Devices;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework.Media;
using System.Net;
using System.Windows.Documents;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Shell;
using System.Xml.Linq;
using System.Device.Location;
using System.Runtime.Serialization;
using first_learn.GeocodeService;
using Microsoft.Phone.Controls.Maps;
using Microsoft.Phone.Tasks;
using Microsoft.Phone;
using System.Windows.Resources;

using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.IO;
using System.Text;
using System.Windows;
using SocketEx;

namespace first_learn
{
    public partial class MainPageFive : PhoneApplicationPage
    {
        Socket mySocket = null;
        ManualResetEvent MyEvent = null;
        private byte[] _imageBytes;
        long length;
        private string serverAddress = "sslab13.cs.purdue.edu";
        private int serverPort = 4546;
        private Stream stm;

        public MainPageFive()
        {
            InitializeComponent();
            ApplicationBar = new ApplicationBar();//声明一个ApplicationBar 

            ApplicationBar.IsVisible = true;//设置应用程序栏可见
            //ApplicationBar.IsVisible = false;
            ApplicationBar.IsMenuEnabled = true;//设置菜单项可用

            ApplicationBarIconButton button1 = new ApplicationBarIconButton(new Uri("/Icons/dark/appbar.share.rest.png", UriKind.Relative));//声明一个Button,并设置其图标路劲。
            button1.Text = "MainPage";//图标显示的名称为Video
            button1.Click += new EventHandler(ToMainPage);//注册Click事件

            ApplicationBarIconButton button2 = new ApplicationBarIconButton(new Uri("/Icons/dark/appbar.feature.search.rest.png", UriKind.Relative));
            button2.Text = "Change City";
            button2.Click += new EventHandler(Change);

            ApplicationBar.Buttons.Add(button1);//将Button添加到应用程序栏中，这样便可以使用该Button了。
            //ApplicationBar.Buttons.Add(button2);

            ApplicationBarMenuItem menuItem1 = new ApplicationBarMenuItem("About");//声明一个MenuItem项，并设置显示文字为电子书
            ApplicationBarMenuItem menuItem2 = new ApplicationBarMenuItem("Rate");
            ApplicationBarMenuItem menuItem3 = new ApplicationBarMenuItem("Exit");

            menuItem1.Click += new EventHandler(menuItem1_Click);//注册MenuItem项的Click事件
            menuItem2.Click += new EventHandler(menuItem2_Click);
            menuItem3.Click += new EventHandler(menuItem3_Click);


            ApplicationBar.MenuItems.Add(menuItem1);//将MenuItem添加到菜单栏中，这样便可以使用该MenuItem了。
            ApplicationBar.MenuItems.Add(menuItem2);
            ApplicationBar.MenuItems.Add(menuItem3);
        }

        private void buttonCapture_Click(object sender, RoutedEventArgs e)
        {
            ShowCameraCaptureTask();
        }

        private void ShowCameraCaptureTask()
        {
            var cameraTask = new CameraCaptureTask();
            cameraTask.Completed += cameraTask_Completed;
            cameraTask.Show();
        }

        private void cameraTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                // Get the image temp file from e.OriginalFileName.
                // Get the image temp stream from e.ChosenPhoto.
                // Don't keep either the stream or rely on the temp
                // file name as they may be vanished!

                // Store the image bytes.
                length = e.ChosenPhoto.Length;
                _imageBytes = new byte[e.ChosenPhoto.Length];
                e.ChosenPhoto.Read(_imageBytes, 0, _imageBytes.Length);
                //Image img = new Image(e.ChosenPhoto);

                MediaLibrary mediaLibrary = new MediaLibrary();
                mediaLibrary.SavePicture("wjw", e.ChosenPhoto);
                //byte[] bytes;
                //BinaryReader br = new BinaryReader(e.ChosenPhoto);
                //bytes = br.ReadBytes(e.ChosenPhoto.Length);

                // Seek back so we can create an image.
                e.ChosenPhoto.Seek(0, SeekOrigin.Begin);
                // Create an image from the stream.
                var imageSource = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
                image1.Source = imageSource;

                
            }
        }

        public static void CaptureElementToAlbum(FrameworkElement element, string saveName)
        {
            using (MemoryStream tempMemoryStream = new MemoryStream())
            {
                WriteableBitmap wb = new WriteableBitmap((int)element.ActualWidth, (int)element.ActualHeight);
                wb.Render(element, null);
                wb.Invalidate();
                wb.SaveJpeg(tempMemoryStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
                tempMemoryStream.SetLength(tempMemoryStream.Position);
                tempMemoryStream.Seek(0, SeekOrigin.Begin);
                MediaLibrary mediaLibrary = new MediaLibrary();
                mediaLibrary.SavePicture(saveName, tempMemoryStream);
            }
        } 


        private IsolatedStorageFileStream StoreFile()
        {
            string fileName = ((BitmapImage)(image1.Source)).UriSource.OriginalString;
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (store.FileExists(fileName))
                {
                    store.DeleteFile(fileName);
                }

                IsolatedStorageFileStream storeFile = store.CreateFile(fileName);
                StreamResourceInfo sri = null;
                Uri uri = new Uri(fileName, UriKind.Relative);
                sri = Application.GetResourceStream(uri);


                BitmapImage bitmap = new BitmapImage();
                bitmap.CreateOptions = BitmapCreateOptions.None;
                bitmap.SetSource(sri.Stream);

                WriteableBitmap wb = new WriteableBitmap(bitmap);
                wb.SaveJpeg(storeFile, wb.PixelWidth, wb.PixelHeight, 0, 100);
                storeFile.Close();

                storeFile = store.OpenFile(fileName, FileMode.Open, FileAccess.Read);
                return storeFile;
            }
        }


        private void LoadFromLocalStorage()
        {
            /*var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
            if (!isoFile.DirectoryExists(imageFolder))
            {
                isoFile.CreateDirectory(imageFolder);
            }

            string filePath = System.IO.Path.Combine(imageFolder, imageFileName);
            using (var imageStream = isoFile.OpenFile(
                filePath, FileMode.Open, FileAccess.Read))
            {
                var imageSource = PictureDecoder.DecodeJpeg(imageStream);
                image1.Source = imageSource;
            }*/
            PhotoChooserTask photo = new PhotoChooserTask();
            photo.Completed += PhotoChooserTaskCompleted;
            photo.ShowCamera = true;
            photo.Show();
        }

        void PhotoChooserTaskCompleted(object sender, PhotoResult e)
        {
            switch (e.TaskResult)
            {
                case TaskResult.OK:
                    image1.Source = new BitmapImage(new Uri(e.OriginalFileName));
                    break;
            }
        }

        private void browser_Click(object sender, RoutedEventArgs e)
        {
            LoadFromLocalStorage();
        }

        private void upload_Click(object sender, RoutedEventArgs e)
        {
            serverPort = 4547;
            var connection = CreateConnection();
            var stream = connection.GetStream();

            var reader = new StreamReader(stream);
            var writer = new StreamWriter(stream);
            //var request = stm;
            

            writer.Write(_imageBytes);
            writer.Flush();
            writer.Close();

            var fullMessage = new StringBuilder();

            string message;
            while ((message = reader.ReadLine()) != null)
            {
                if (string.IsNullOrWhiteSpace(message))
                    break;

                fullMessage.AppendLine(message);
            }

            textBlock2.Text = fullMessage.ToString();


            serverPort = 4546;
            //send image info
            var connection2 = CreateConnection();
            var stream2 = connection.GetStream();

            var reader2 = new StreamReader(stream2);
            var writer2 = new StreamWriter(stream2);
            var request2 = "SEND IMAGEINFO "+textBlock2.Text+" "+"wjw#jpg#address#West_Lafayette,IN";

            writer2.WriteLine(request2);
            writer2.Flush();

        }


        private TcpClient CreateConnection()
        {
            var connection = new TcpClient(serverAddress, serverPort);

            return connection;
        }

        void Change(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPageThree.xaml", UriKind.Relative));
        }

        void ToMainPage(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));

        }

        private void menuItem1_Click(object sender, System.EventArgs e)
        {
            // About 
            MessageBox.Show("About this app.");
        }

        private void menuItem2_Click(object sender, System.EventArgs e)
        {
            // Rate 
            MessageBox.Show("Rate this app!");
        }


        private void menuItem3_Click(object sender, System.EventArgs e)
        {
            // exit 
            throw new Exception("exit");
        }


    }
}